import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { DATA_ENTRY, FormGroup } from '@/src/components';
import style from './index.less';
import moment from 'moment';

const checkStatus = (key) => {
  let str = '';
  switch (key) {
    case '1':
      str = '可用';
      break;
    case '2':
      str = '不可用';
      break;
    case '3':
      str = '创建审批中';
      break;
    case '4':
      str = '修改审批中';
      break;
    case '5':
      str = '删除审批中';
      break;
  }
  return str;
};
class FormRenderC extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      orgDisabled: false,
      shortName: '',
      shortNameArr: [], // 交易对手短名
      longName: '',
      role: [],
      issuerFieldValue: '',
      issuerEconomyValue: '',
      issuerScaleValue: '',
      countryStatus: '',
    };
    this.FormGroupRefbasic = React.createRef();
    this.FormGroupRefstatus = React.createRef();
    this.FormGroupRefattr = React.createRef();
    this.FormGroupRefissuer = React.createRef();
    this.FormGroupReforgan = React.createRef();
  }

  componentDidMount() {
    // 父组件对本组件的引用
    this.props.onRef(this);
    this.setState({
      countryStatus: this.props.countryStatus,
    });
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    // 初始化角色为产品 母机构设置为disable
    if (JSON.stringify(prevProps.info) !== JSON.stringify(this.props.info)) {
      this.setState({
        orgDisabled: this.props.info.isProduct == '0',
      });
      if (this.props.info.role && this.props.info.role.length > 0) {
        this.roleChange(this.props.info.role);
      }
    }
    if (JSON.stringify(prevProps.countryStatus) != JSON.stringify(this.props.countryStatus)) {
      this.setState({
        countryStatus: this.props?.countryStatus,
      });
    }
  }

  roleChange = (e) => {
    if (typeof this.props.roleChange !== 'undefined') {
      this.props.roleChange(e.includes('1'), e.includes('2'));
    }
  };

  isProductChange = (e) => {
    if (e == 1) {
      this.setState({ orgDisabled: false });
    } else {
      this.setState({ orgDisabled: true });
      this.FormGroupRefbasic.current?.formRef.current.setFieldsValue({
        parentOrg: undefined,
      });
    }
  };

  getFormData = async () => {
    // 获取表单数据
    const { type, status } = this.props;
    const { params } = this.props.that.state;
    const a = await this.FormGroupRefbasic.current?.getFormGroupData();
    const b = await this.FormGroupRefstatus.current?.getFormGroupData();
    const c = await this.FormGroupRefattr.current?.getFormGroupData();
    const d = await this.FormGroupRefissuer.current?.getFormGroupData();
    const e = await this.FormGroupReforgan.current?.getFormGroupData();
    const fieldsValue = { ...a, ...b, ...c, ...d, ...e };
    if (fieldsValue.timeOfExpiration != undefined) {
      fieldsValue.timeOfExpiration = moment(fieldsValue.timeOfExpiration).format('YYYY-MM-DD');
    }
    sessionStorage.setItem(type, '1'); // 所有的表单校验成功之后 告知给父组件
    if (Object.keys(params).length) {
      if (type == 'basic') {
        fieldsValue.needApproval = fieldsValue.needApproval == '0';
        // 交易对手返回的是value 接口需要传title
        params.counterparties.basicInfo = { ...params.counterparties.basicInfo, ...fieldsValue, shortName: this.state.shortName };
      } else if (type == 'attr') {
        params.counterparties.attribute = { ...params.counterparties.attribute, ...fieldsValue };
      } else if (type == 'issuer') {
        params.counterparties.attribute = { ...params.counterparties.attribute, ...fieldsValue };
      } else {
        params.organ.basicInfo = { ...params.organ.basicInfo, ...fieldsValue };
      }
    }
  };

  disabledDate(current) {
    return current < moment().subtract(1, 'days');
  }

  // 交易对手短名选择
  shortNameChange = (e, option) => {
    if (e) {
      this.setState({
        longName: e?.fullName,
        shortName: e?.title,
      });
      this.FormGroupRefbasic.current.formRef.current.setFieldsValue({
        longName: e?.fullName,
        shortName: e?.title,
      });
    }
  };

  // 判断是发行人备注否为必填项
  requiredValue = () => {
    const { issuerFieldValue, issuerEconomyValue, issuerScaleValue } = this.state;
    let issuerField, issuerEconomy, issuerScale;
    const { info } = this.props;
    issuerField = issuerFieldValue ? issuerFieldValue : info.issuerField;
    issuerEconomy = issuerEconomyValue ? issuerEconomyValue : info.issuerEconomy;
    issuerScale = issuerScaleValue ? issuerScaleValue : info.issuerScale;
    return issuerField == '99' && issuerEconomy == '99' && issuerScale == '99';
  };

  // 改变国家地区选择
  changeCountries = (e) => {
    this.props.changeCountryStatus &&
      this.props.changeCountryStatus({
        countryStatus: e,
      });
  };

  render() {
    const { type, status, info } = this.props;
    const { parentOrgList, parentOrgListSelect } = this.props.that.state;
    const { longName, role, shortNameArr, countryStatus } = this.state;
    const {
      globalM: {
        dataDictionary: { COUNTER_PARTY_COUNTRY = [], COUNTER_PARTY_ROLE = [], ISSUER_BY_SIZE = [], ISSUER_BY_TECHNOLOGY = [], ISSUER_BY_ECONOMIC = [], COUNTERPARTY_TYPE = [] },
      },
    } = this.props;
    const selectList = [
      { value: '0', title: '是' },
      { value: '1', title: '否' },
    ];
    const orgList = status == 'edit' ? parentOrgListSelect || [] : parentOrgList;
    const counterpartyDisabled = status == 'edit' ? !!info.shortName : status == 'query'; // 交易对手长名或短名，若有未填写的情况，在编辑时，允许编辑。
    return (
      <div>
        {type == 'basic' ? (
          <FormGroup
            autoLayout={false}
            rowNumber={3}
            onRef={(ref) => {
              this.FormGroupRefbasic.current = ref;
            }}
            dataSource={[
              {
                dataIndex: 'shortName',
                title: '交易对手短名',
                type: DATA_ENTRY.TRADINGCOMPANY,
                onChange: this.shortNameChange,
                dataType: 1,
                allowClear: true,
                disabled: counterpartyDisabled,
                initialValue: info.shortName,
                rules: [{ required: true, message: '请输入交易对手短名' }],
                InputValueSave: true,
              },
              {
                dataIndex: 'longName',
                type: DATA_ENTRY.INPUT,
                allowClear: true,
                title: '交易对手长名',
                disabled: counterpartyDisabled,
                initialValue: info.longName || longName,
                rules: [{ required: true, message: '请输入交易对手长名!' }],
              },
              {
                dataIndex: 'role',
                type: DATA_ENTRY.SELECT,
                title: '交易对手角色',
                dataSource: COUNTER_PARTY_ROLE.map((item) => {
                  const obj = {
                    title: item.value,
                    value: item.code,
                  };
                  return obj;
                }),
                onChange: this.roleChange,
                isMultiple: true,
                disabled: status == 'query',
                initialValue: info.role && info.role.length > 0 ? info.role : role,
                rules: [{ required: true, message: '请选择交易对手角色' }],
              },
              {
                dataIndex: 'isProduct',
                type: DATA_ENTRY.SELECT,
                title: '是否为产品',
                dataSource: selectList,
                disabled: status == 'query',
                initialValue: status == 'query' || status == 'edit' ? info.isProduct : undefined,
                rules: [{ required: true, message: '请选择是否为产品' }],
                onChange: this.isProductChange,
              },
              {
                dataIndex: 'parentOrg',
                type: DATA_ENTRY.SELECT,
                title: '母机构',
                allowClear: true,
                dataSource: orgList,
                disabled: status == 'query' || this.state.orgDisabled,
                initialValue: info.parentOrg,
              },
              {
                dataIndex: 'countries',
                type: DATA_ENTRY.SELECT,
                title: '国家地区',
                allowClear: true,
                dataSource: COUNTER_PARTY_COUNTRY.map((item) => {
                  const obj = {
                    title: item.value,
                    value: item.code,
                  };
                  return obj;
                }),
                disabled: status == 'query',
                initialValue: info.countries,
                rules: [{ required: true, message: '请选择国家地区' }],
                filterOption: false,
                onChange: this.changeCountries,
              },
              {
                dataIndex: 'needApproval',
                type: DATA_ENTRY.SELECT,
                title: '是否需要审批',
                dataSource: selectList,
                disabled: status == 'query',
                initialValue: status == 'query' || status == 'edit' ? (info.needApproval ? '0' : '1') : undefined,
                rules: [{ required: true, message: '请选择' }],
              },
              {
                dataIndex: 'timeOfExpiration',
                type: DATA_ENTRY.SINGLEDATE,
                title: ' 失效时间',
                initialValue: info.timeOfExpiration ? moment(info.timeOfExpiration) : moment('2199-12-31'),
                rules: [{ required: true, message: '请选择失效时间' }],
                disabled: status == 'query',
              },
            ]}
          />
        ) : null}

        {type == 'status' ? (
          <FormGroup
            autoLayout={false}
            rowNumber={3}
            onRef={(ref) => {
              this.FormGroupRefstatus.current = ref;
            }}
            dataSource={[
              {
                dataIndex: 'status',
                type: DATA_ENTRY.INPUT,
                title: '可用状态',
                disabled: true,
                initialValue: checkStatus(info.status) || undefined,
              },
              {
                dataIndex: 'creator',
                type: DATA_ENTRY.INPUT,
                title: '创建人',
                disabled: true,
                initialValue: info.creator || undefined,
              },
              {
                dataIndex: 'timeOfCreation',
                type: DATA_ENTRY.INPUT,
                title: '创建时间',
                disabled: true,
                initialValue: info.timeOfCreation ? moment(info.timeOfCreation).format('YYYY-MM-DD') : undefined,
              },
              {
                dataIndex: 'modifer',
                type: DATA_ENTRY.INPUT,
                title: '上一次更改人',
                disabled: true,
                initialValue: info.modifer || undefined,
              },
              {
                dataIndex: 'timeOfLastModification',
                type: DATA_ENTRY.INPUT,
                title: '上一次更改时间',
                disabled: true,
                initialValue: info.timeOfLastModification ? moment(info.timeOfLastModification).format('YYYY-MM-DD') : undefined,
              },
            ]}
          />
        ) : null}
        {type == 'attr' ? (
          <FormGroup
            autoLayout={false}
            rowNumber={3}
            onRef={(ref) => {
              this.FormGroupRefattr.current = ref;
            }}
            dataSource={[
              {
                dataIndex: 'interBankAccount',
                type: DATA_ENTRY.INPUT,
                title: '银行间账户名称',
                disabled: status == 'query',
                initialValue: info.interBankAccount,
              },
              {
                dataIndex: 'newFourCategories',
                type: DATA_ENTRY.SELECT,
                title: '是否新四类',
                dataSource: selectList,
                disabled: status == 'query',
                allowClear: true,
                initialValue: status == 'query' || status == 'edit' ? info.newFourCategories : undefined,
                filterOption: false,
              },
              {
                dataIndex: 'seatNumber',
                type: DATA_ENTRY.INPUT,
                title: '大宗平台交易所席位',
                disabled: status == 'query',
                initialValue: info.seatNumber,
              },
              {
                dataIndex: 'nafmii',
                type: DATA_ENTRY.SELECT,
                title: '是否签署NAFMII协议',
                dataSource: selectList,
                disabled: status == 'query',
                allowClear: true,
                initialValue: status == 'query' || status == 'edit' ? info.nafmii : undefined,
                filterOption: false,
              },
              {
                dataIndex: 'institutionalTrader',
                type: DATA_ENTRY.INPUTNUMBER,
                title: '机构交易员代码(前三位)',
                disabled: status == 'query',
                precision: 0,
                initialValue: info.institutionalTrader,
                rules: [{ pattern: /^[0-9]{3}$/, message: '请输入三位数字' }],
              },
              {
                dataIndex: 'counterpartyType',
                type: DATA_ENTRY.SELECT,
                title: '交易对手类型',
                dataSource: COUNTERPARTY_TYPE.map((item) => {
                  const obj = {
                    title: item.value,
                    value: item.code,
                  };
                  return obj;
                }),
                disabled: status == 'query',
                allowClear: true,
                initialValue: status == 'query' || status == 'edit' ? info.counterpartyType : undefined,
                filterOption: false,
                rules: [{ required: false, message: '请选择交易对手类型!' }],
              },
            ]}
          />
        ) : null}
        {type == 'issuer' ? (
          <FormGroup
            onRef={(ref) => {
              this.FormGroupRefissuer.current = ref;
            }}
            autoLayout={false}
            rowNumber={3}
            dataSource={[
              {
                dataIndex: 'issuerScale',
                type: DATA_ENTRY.SELECT,
                title: '发行机构类型（按规模划分）',
                dataSource: ISSUER_BY_SIZE.map((item) => {
                  const obj = {
                    title: item.value,
                    value: item.code,
                  };
                  return obj;
                }),
                disabled: status == 'query',
                initialValue: info.issuerScale,
                labalWrap: true,
                rules: [{ required: true, message: '请选择发行机构类型（按规模划分）!' }],
                onChange: (e) => {
                  this.setState({
                    issuerScaleValue: e,
                  });
                },
                span: 8,
              },
              {
                dataIndex: 'issuerField',
                type: DATA_ENTRY.SELECT,
                title: '发行机构类型（按技术领域划分）',
                dataSource: ISSUER_BY_TECHNOLOGY.map((item) => {
                  const obj = {
                    title: item.value,
                    value: item.code,
                  };
                  return obj;
                }),
                disabled: status == 'query',
                initialValue: info.issuerField,
                labalWrap: true,
                rules: [{ required: true, message: '请选择发行机构类型（按技术领域划分）!' }],
                onChange: (e) => {
                  this.setState({
                    issuerFieldValue: e,
                  });
                },
                span: 8,
              },
              {
                dataIndex: 'issuerEconomy',
                type: DATA_ENTRY.SELECT,
                title: '发行机构类型（按经济类型划分）',
                dataSource: ISSUER_BY_ECONOMIC.map((item) => {
                  const obj = {
                    title: item.value,
                    value: item.code,
                  };
                  return obj;
                }),
                disabled: status == 'query',
                initialValue: info.issuerEconomy,
                labalWrap: true,
                rules: [{ required: true, message: '请选择发行机构类型（按经济类型划分）!' }],
                onChange: (e) => {
                  this.setState({
                    issuerEconomyValue: e,
                  });
                },
                span: 8,
              },
              {
                dataIndex: 'issuerIndustry',
                type: DATA_ENTRY.FUNDAPPLICATIONINDUSTRYC,
                title: '发行机构所属行业',
                disabled: status == 'query',
                initialValue: info?.issuerIndustry,
                rules: [{ required: true, message: '请选择发行机构所属行业!' }],
                span: 8,
              },
              {
                hide: countryStatus != '1',
                type: DATA_ENTRY.ADDRESSC,
                provinceDataIndex: 'province',
                cityDataIndex: 'city',
                provInit: info?.province,
                cityInit: info?.city,
                disabled: status == 'query',
                span: 16,
              },
              {
                dataIndex: 'issuerRemark',
                type: DATA_ENTRY.INPUT,
                title: '备注',
                disabled: status == 'query',
                initialValue: info.issuerRemark,
                showALLValue: true,
                showTextArea: true,
                rules: [{ required: this.requiredValue(), message: '请输入备注!' }],
                span: 24,
              },
            ]}
          />
        ) : null}
        {type == 'organ' ? (
          <FormGroup
            autoLayout={false}
            rowNumber={3}
            onRef={(ref) => {
              this.FormGroupReforgan.current = ref;
            }}
            dataSource={[
              {
                dataIndex: 'creditCode',
                type: DATA_ENTRY.INPUT,
                title: '社会统一信用代码',
                disabled: status == 'query',
                initialValue: info.creditCode || undefined,
                span: 8,
              },
              {
                dataIndex: 'contact',
                type: DATA_ENTRY.INPUT,
                title: '联系方式',
                disabled: status == 'query',
                initialValue: info.contact || undefined,
                span: 8,
              },
              {
                dataIndex: 'domicile',
                type: DATA_ENTRY.INPUT,
                title: '住所',
                disabled: status == 'query',
                initialValue: info.domicile || undefined,
                span: 8,
              },
              {
                dataIndex: 'business',
                type: DATA_ENTRY.INPUT,
                title: '经营范围',
                disabled: status == 'query',
                initialValue: info.business || undefined,
                span: 24,
              },
            ]}
          />
        ) : null}
      </div>
    );
  }
}

export default connect(({ counterpartyInformationM, globalM, loading }) => ({
  counterpartyInformationM,
  globalM,
  loading,
}))(FormRenderC);
